Skip to main content
POST
/
v1
/
agents
/
{agent_id}
/
invoke
/
stream
Invoke Agent (Stream)
curl --request POST \
  --url https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
  "input": {
    "text": "<string>",
    "files": [
      "<string>"
    ],
    "user": {
      "id": "<string>",
      "first_name": "<string>",
      "last_name": "<string>",
      "email": "<string>",
      "additional_attributes": {}
    }
  },
  "id": "<string>",
  "payload_extension": {},
  "parent_execution_id": "<string>",
  "worker_id": "<string>",
  "source": "<string>",
  "output_format": "text",
  "output_schema": {},
  "run_locally": true,
  "additional_context": "<string>",
  "expected_output": "<string>",
  "events_streaming": true,
  "mcp_servers": [
    {}
  ],
  "triggering_agent_id": "<string>",
  "title": "<string>"
}'
"<any>"
Execute an agent task with real-time streaming responses. This endpoint returns Server-Sent Events (SSE) that provide live updates as the agent processes the task. Perfect for interactive applications and real-time user interfaces.

Path Parameters

agent_id
string
required
Unique identifier of the agent to invoke (UUID format)

Request Body

input
object
required
Agent execution input containing the task details
output_format
string
Desired output format. Valid values: text | json | markdownDefault: text
  • text: Plain text response
  • json: Structured JSON output (use with output_schema for validation)
  • markdown: Formatted markdown response
output_schema
object
JSON Schema to validate and structure the agent’s output. When provided with output_format: "json", the agent will return data conforming to this schema.Example:
{
  "type": "object",
  "required": ["summary", "insights"],
  "properties": {
    "summary": {"type": "string"},
    "insights": {"type": "array", "items": {"type": "string"}}
  }
}
events_streaming
boolean
Enable detailed event streaming for granular progress tracking. When true, emits events for tool calls, intermediate steps, and execution progress.Default: falseRecommended: Set to true for this endpoint to get maximum visibility into agent execution.
additional_context
string
Additional context to guide the agent’s behavior. Use this to specify tone, audience, constraints, or background information.Example: "This is for executive leadership. Use professional tone and focus on business impact."
expected_output
string
Description of the expected output format, length, or structure. Helps guide the agent to produce the desired result.Example: "A 500-word summary with 3 key recommendations and supporting data."
title
string
Human-readable title for the task. Useful for identification and organization in task lists.Example: "Real-time Data Analysis"
parent_execution_id
string
UUID of the parent task if this is a sub-task. Used for multi-agent workflows and task hierarchies.Example: "550e8400-e29b-41d4-a716-446655440000"
triggering_agent_id
string
UUID of the agent that triggered this task. Used for tracking agent-to-agent delegation.Example: "7c9e6679-7425-40de-944b-e07fc1f90ae7"
payload_extension
object
Custom metadata to attach to the task. Any valid JSON object. Useful for tracking, routing, or application-specific data.Example:
{
  "request_id": "REQ-2025-001",
  "priority": "high",
  "stream_session_id": "stream-789"
}
mcp_servers
array
Array of Model Context Protocol (MCP) server configurations to use during execution. Enables integration with external tools and services.Example:
[
  {
    "name": "real-time-data",
    "config": {"refresh_interval": 5}
  }
]
source
string
Identifier for the source system or application that created this task. Useful for analytics and debugging.Example: "chat-widget" | "mobile-app" | "websocket-client"

Example Requests

Basic Streaming Request

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Write a story about AI"
       }
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

With Detailed Event Streaming

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Research AI trends and create a report"
       },
       "events_streaming": true,
       "title": "AI Trends Research"
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

File Processing with Progress Tracking

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Analyze these documents",
         "files": [
           "https://example.com/report1.pdf",
           "https://example.com/report2.pdf"
         ]
       },
       "events_streaming": true,
       "output_format": "markdown",
       "additional_context": "Focus on key metrics and trends"
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

Structured Output with Streaming

curl -X POST -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "input": {
         "text": "Extract insights from customer feedback"
       },
       "output_format": "json",
       "output_schema": {
         "type": "object",
         "properties": {
           "sentiment": {"type": "string"},
           "themes": {"type": "array", "items": {"type": "string"}},
           "recommendations": {"type": "array", "items": {"type": "string"}}
         }
       },
       "events_streaming": true
     }' \
     https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream

Response Format

This endpoint returns Server-Sent Events (SSE) with Content-Type: text/event-stream

Event Stream Format

Events are sent in SSE format:
data: {"type": "task_started", "task_id": "...", "timestamp": "..."}

data: {"type": "content_chunk", "content": "...", "is_final": false}

data: {"type": "task_completed", "task_id": "...", "result": "..."}

Event Types

task_started
event
Sent when the task begins execution
content_chunk
event
Sent for each piece of generated content
task_completed
event
Sent when the task finishes successfully
error
event
Sent if an error occurs during execution

Example: JavaScript Client

const response = await fetch('https://api.xpander.ai/v1/agents/{agent_id}/invoke/stream', {
  method: 'POST',
  headers: {
    'x-api-key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    input: {
      text: 'Analyze this data',
      files: []
    },
    events_streaming: true
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const event = JSON.parse(line.slice(6));
      console.log('Event:', event);
      
      if (event.type === 'task_completed') {
        console.log('Result:', event.result);
      }
    }
  }
}

Notes

  • The agent must have deployment_type: serverless or be a running container
  • Connection stays open until task completes or errors
  • Set appropriate timeout values for long-running tasks
  • Handle connection errors and implement retry logic

See Also

  • [Invoke Agent (Sync)](/API reference/v1/agents/invoke-sync) - For quick tasks with immediate results
  • [Invoke Agent (Async)](/API reference/v1/agents/invoke-async) - For long-running tasks with polling
  • [Get Task](/API reference/v1/tasks/get-task) - Retrieve task details after streaming completes

Authorizations

x-api-key
string
header
required

API Key for authentication

Path Parameters

agent_id
string
required

Body

application/json
input
object
required
id
string | null
payload_extension
object | null
parent_execution_id
string | null
worker_id
string | null
source
string | null
output_format
enum<string> | null
default:text
Available options:
text,
markdown,
json
output_schema
object | null
run_locally
boolean | null
default:false
additional_context
string | null
expected_output
string | null
events_streaming
boolean | null
default:false
mcp_servers
Mcp Servers · object[] | null
triggering_agent_id
string | null
title
string | null

Response

Successful Response

The response is of type any.